/**
 * Created by wugang5 on 2016/10/25.
 * 搜索控件
 */
define(["jquery", "jstorage","ecp.utils.i18n"], function ($, jStorage, locale) {
	//搜索模板
    var searchTemplate = {
        //立即搜索模式主模板
        one: '<div class="search-input-jishi" style="width: {width}"> ' +
        '<i class="iconSearch"></i> ' +
        '<input type="text" required class="form-control" placeholder="{placeholder}">' +
        '<i id="clearInputBtn" class="btnClear" title="清空" ng-title="locale.clearAll"></i>{history}' +
        '</div>',
        //非立即搜索模式主模板
        two: '<div class="search-input" style="width: {width}" >' +
        '<input type="text" required class="form-control" value="" placeholder="{placeholder}">' +
        '<i id="clearInputBtn" class="btnClear" title="清空" ng-title="locale.clearAll"></i>{history}' +
        '<button class="btnSearch"></button>' +
        '</div>',
        //历史记录模板
        historyHtml: '<div class="search-history" style="width:{width}">' +
        '<ul>' +
        '<li class="li1" ng-bind="locale.historyRecords">历史记录</li>' +
        '</ul>' +
        '</div>',
        //单个历史记录模板
        historyItem: '<li><span>{text}</span><i class="btnClear" title="{del}" ng-title="locale.del" ></i></li>'
    };
    var _locale = locale.search;
    //默认参数
    var defaults = {
        //输入框宽度
        width: '220px',
        //placeholder
        placeholder: _locale.placeholder,
        //渲染容器
        container: '',
        //缓存主键
        storeKey: '',
        //是否显示历史记录
        showHistory: true,
        //立即搜索模式
        isImmediateMode: true,
        //回调函数
        callback: function () {
        }
    };

    /**
     * 构造函数
     * @param options 参数
     * @constructor
     */
    function Plugin(options) {
        if (options.isImmediateMode === false) {
            defaults.placeholder = _locale.placeholder2;
        }
        this.options = $.extend({}, defaults, options || {});
        this.container = $(this.options.container);
        if (!this.container.length) {
            return;
        }
        this.render();
        this.bindEvent();
    }

    Plugin.prototype = {
        /**
         * 渲染主方法
         */
        render: function () {
            var _opts = this.options,
                template = _opts.isImmediateMode ? searchTemplate.one : searchTemplate.two;
            template = template.replace(/{history}/g, _opts.showHistory ? searchTemplate.historyHtml : '');
            template = template.replace(/{width}/g, _opts.width).replace(/{placeholder}/g, _opts.placeholder);
            //生成搜索控件
            this.container.html(template);
            //国际化
            $.replaceI18nText(_locale, this.container);
            $.replaceI18nAttr(_locale, this.container, "title");
            this.$clearInputBtn = $('#clearInputBtn', this.container);
            this.$searchInput = $('input[type="text"]', this.container);
            !_opts.isImmediateMode && (this.$searchBtn = $('.btnSearch', this.container));
            //初始化Storage和历史记录数据列表
            if (_opts.showHistory && _opts.storeKey) {
                this.$history = $('.search-history > ul', this.container);
                this.initStorage();
                var data = this.getStorage();
                this.initHistoryList(data);
            }
        },
        /**
         * 绑定事件
         */
        bindEvent: function () {
            this.bindClearBtn();
            this.bindInput();
            this.bindSearchBtn();
            this.bindClearHistory();
            this.bindDocument();
        },
        /**
         * 绑定输入框内的清除按钮事件
         */
        bindClearBtn: function () {
            var that = this;
            that.$clearInputBtn.off('click').on('click', function () {
                var $this = $(this);
                that.$searchInput.val("").focus();
                $this.fadeOut("fast").hide();
                //执行回调
                (typeof that.options.callback === 'function') && that.options.callback.call(this, "");
            });
        },
        /**
         * 绑定输入框事件
         */
        bindInput: function () {
            var isEnterKey = false,
                that = this;
            that.$searchInput.off('keyup').on('keyup', function (event) {
                var e = event || window.event;
                var $this = $(this);
                var searchVal = $this.val();
                if (searchVal == '') {
                    that.$clearInputBtn.fadeOut("fast").hide();
                } else {
                    that.$clearInputBtn.fadeIn("fast").show();
                }
                isEnterKey = false;
                //键盘enter
                if (e.keyCode == 13) {
                    isEnterKey = true;
                    (typeof that.options.callback === 'function') && that.options.callback.call(this, searchVal);
                    //更新搜索历史记录
                    if (that.options.showHistory && that.options.storeKey) {
                        that.addHistory(searchVal);
                    }
                    that.hideHistoryList();
                } else if (that.options.isImmediateMode) {
                    //连续输入清除定时器
                    if (this.timeoutID) {
                        clearTimeout(this.timeoutID);
                    }
                    this.timeoutID = setTimeout(function () {
                        if (!isEnterKey) {
                            (typeof that.options.callback === 'function') && that.options.callback.call(this, searchVal);
                            //更新搜索历史记录
                            if (that.options.showHistory && that.options.storeKey) {
                                that.addHistory(searchVal);
                            }
                        }
                    }, 300);
                }
            });
            //输入框focus时显示历史记录数据
            if (that.options.showHistory && that.options.storeKey) {
                that.$searchInput.on('focus', function () {
                    that.showHistoryList();
                    if(!that.options.isImmediateMode){
                    	that.$searchBtn.addClass("active");
                    }
                });
            }
        },
        /**
         * 绑定非立即搜索模式中的搜索按钮
         */
        bindSearchBtn: function () {
            var that = this;
            if (!that.options.isImmediateMode) {
                that.$searchBtn.off('click').on('click', function () {
                    (typeof that.options.callback === 'function') && that.options.callback.call(this, that.getValue());
                    //更新搜索历史记录
                    if (that.options.showHistory && that.options.storeKey) {
                        that.addHistory(that.getValue());
                    }
                    that.hideHistoryList();
                });
            }
        },
        /**
         * 绑定历史记录列表中的事件
         */
        bindClearHistory: function () {
            var that = this;
            if (that.options.showHistory) {
                $('.search-history', that.container).delegate('li', 'mouseover mouseout', function (e) {
                    //显示或者隐藏删除按钮
                    $(this).find('i').toggle();
                });
                $('.search-history', that.container).delegate('li', 'click', function (e) {
                    var $this = $(this);
                    var value = $this.find("span").text();
                    //删除当前dom并更新历史记录缓存数据
                    if (e.target.className == "btnClear") {
                        $this.remove();
                        that.removeHistory(value);
                        e.stopPropagation();
                    } else {
                        //将选中的列表数据作为关键字并触发搜索
                        that.$searchInput.val(value);
                        that.$searchInput.trigger('keyup');
                        //隐藏历史列表
                        that.hideHistoryList();
                    }
                });
            }
        },
        /**
         * 点击空白处关闭历史记录列表
         */
        bindDocument: function () {
            var that = this;
            $(document).on('click.search', function (e) {
                e = e || window.event;
                var target = $(e.target);
                if (target.closest(that.container).length == 0) {
                    that.hideHistoryList();
                    if(!that.options.isImmediateMode){
                    	that.$searchBtn.removeClass("active");
                    }
                }
            });
        },
        /**
         * 初始化历史记录列表
         * @param data
         */
        initHistoryList: function (data) {
            var that = this;
            if($.isArray(data)){
                data.forEach(function (value) {
                    that.buildHistoryItem(value);
                });
            }
        },
        /**
         * 生成单个li片段
         * @param value
         */
        buildHistoryItem: function (value) {
            this.$history.find("li.li1").after(searchTemplate.historyItem.replace(/{text}/g, value).replace(/{del}/g, _locale["del"]));
        },
        /**
         * 删除最后一个历史记录
         */
        removeHistoryItem: function () {
            this.$history.find("li:last-child").remove();
        },
        /**
         * 初始化缓存
         * @returns {*}
         */
        initStorage: function () {
            var data = this.getStorage();
            if (data == null) {
                this.setStorage([]);
            }
        },
        /**
         * 获取缓存
         * @returns {Mixed}
         */
        getStorage: function () {
            return $.jStorage.get(this.options.storeKey);
        },
        /**
         * 设置缓存
         * @param value
         */
        setStorage: function (value) {
            $.jStorage.set(this.options.storeKey, value);
        },
        /**
         * 添加历史记录
         * @param value
         */
        addHistory: function (value) {
            if (value != "") {
                var data = this.getStorage();
                var index = data && data.indexOf(value);
                //重复不添加
                if (index === -1) {
                    data.push(value);
                    this.buildHistoryItem(value);
                }
                //删除第一个
                if (data.length > 5) {
                    data.splice(0, 1);
                    this.removeHistoryItem();
                }
                //重置缓存
                this.setStorage(data);
            }
        },
        /**
         * 删除历史记录
         * @param value
         */
        removeHistory: function (value) {
            var data = this.getStorage();
            var index = data && data.indexOf(value);
            if (index !== -1) {
                data.splice(index, 1);
            }
            this.setStorage(data);
        },
        /**
         * 显示历史数据列表
         */
        showHistoryList: function () {
            //默认有一个li标签
            if (this.$history.children().length > 1) {
                $(".search-history", this.container).show();
            }
        },
        /**
         * 隐藏历史记录列表
         */
        hideHistoryList: function () {
            $(".search-history", this.container).hide();
        },
        /**
         * 获取输入框的值
         */
        getValue: function () {
            return this.$searchInput.val();
        }
    };
    return {
        /**
         * 渲染入口
         * @param options
         * @returns {Plugin}
         */
        render: function (options) {
            var plugin = new Plugin(options);
            return plugin;
        }
    }
});